package com.jk.generator;


import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.querys.MySqlQuery;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.fill.Column;
import com.baomidou.mybatisplus.generator.keywords.MySqlKeyWordsHandler;
import com.baomidou.mybatisplus.generator.query.SQLQuery;
import com.jk.common.core.controller.BaseController;
import lombok.extern.slf4j.Slf4j;

import java.sql.Types;
import java.util.Collections;
import java.util.HashMap;

/*
    数据层内容生成
 */
@Slf4j
public class MybatisPlusEntityGenerator {
    public static final String modulename = "cms";
    public static final String[] TABLE_PREFIX_ARR = {"svy_", "biz_", "cms_", "emo_"};
    public static final String DOMAIN_BASE_ENTITY = "com.jk.common.core.domain.BaseEntity";
    public static final String[] BASE_COLUMNS = {"create_by", "create_time", "update_time", "update_by", "version", "remark"/*,"deleted"*/};
    // DAO的包路径
    private static String parentPackage = "com.unte.mes";

    // 生成输出目录，定位到工程的java目录下
    private static String outputDir = "E:/gen_temp/src-plus";
    // 生成类的作者
    private static String author = "Amber";
    // 数据源相关配置
    //
    //private static String url = "jdbc:mysql://192.168.100.221:3306/mes_device?autoReconnect=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=CONVERT_TO_NULL&useSSL=false&serverTimezone=UTC";
    private static String url = "jdbc:mysql://192.168.100.221:3306/u_mes?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8";
    private static String driverName = "com.mysql.cj.jdbc.Driver";
    private static String userName = "root";
    private static String userPwd = "123456";

    // 待生成的表名，注意是覆盖更新
    private static String[] tableNames;

    static {

        tableNames = new String[]{
//                "svy_tiku_catalog"
//                "biz_emotion_type",
//                "emo_happy_level",
//                "emo_hlbean",
//                "emo_hlbean_type",
//                "emo_risk_ratio",
//                "emo_user",
//                "biz_training",
                "cms_banner",
                "cms_article",

//                "cms_notice",
//                "cms_news",

                /* "wxmp_user",

                 "sys_site"*/
                /* "svy_survey_tags",
                 "svy_answer_option_xref",
                 "svy_survey",
                 "svy_question",
                 "svy_option",
                 "svy_tiku",
                 "svy_answer"*/

                /* "biz_advice",
                 "biz_advice_image",
                 "biz_advice_tags",
                 "biz_advice_thumbs_up",
                 "biz_appraise",
                 "biz_appraise_image",
                 "biz_communicate",
                 "biz_communicate_assign",
                 "biz_image",
                 "biz_moments",
                 "biz_moments_image",
                 "biz_news",
                 "biz_notice",
                 "biz_training",
                 "biz_training_tags",
                 "biz_user",
                 "biz_user_attendance",
                 "biz_user_healthy",
                 "biz_user_hlbean"*/

        };
    }


    public static void main(String[] args) {
        FastAutoGenerator
                .create(url, userName, userPwd)
                .injectionConfig(builder -> {
                    builder.beforeOutputFile((tableInfo, map) -> {
                        log.info("---- tableInfo {},  objectMap {}", tableInfo.getEntityName(), map.size());
                    }).customMap(new HashMap<>());

                })

                .globalConfig(builder -> {
                    builder.disableOpenDir()
                            .author(author) // 设置作者
                            //.enableSwagger() // 开启 swagger 模式
                            .enableSpringdoc()
                            //.fileOverride() // 覆盖已生成文件
                            .outputDir(outputDir + "/main/java"); // 指定输出目录
                })
                .dataSourceConfig(builder -> builder
                        .dbQuery(new MySqlQuery())
                        .typeConvert(new MySqlTypeConvert())
                        //.schema("")
                        .keyWordsHandler(new MySqlKeyWordsHandler())
                        .databaseQueryClass(SQLQuery.class)
                        .typeConvertHandler((globalConfig, typeRegistry, metaInfo) -> {
                            int typeCode = metaInfo.getJdbcType().TYPE_CODE;
                            if (typeCode == Types.SMALLINT) {
                                // 自定义类型转换
                                return DbColumnType.INTEGER;
                            }
                            return typeRegistry.getColumnType(metaInfo);

                        }))
                .packageConfig(builder -> {
                    builder.parent(parentPackage) // 设置父包名
                            .moduleName(modulename) // 设置父包模块名
                            .entity("domain")
                            .pathInfo(Collections.singletonMap(OutputFile.xml,
                                    outputDir + "/main/resources/mapper/" + modulename)); // 设置mapperXml生成路径
                })
                .strategyConfig(builder -> {
                    builder
                            .addInclude(tableNames)
                            .addTablePrefix(TABLE_PREFIX_ARR)

                            .controllerBuilder().enableFileOverride().enableRestStyle()
                            //.enableHyphenStyle()

                            .superClass(BaseController.class)
                            .mapperBuilder().enableFileOverride()

                            .serviceBuilder().enableFileOverride()
                            //.formatServiceFileName("%sService")
                            //.formatServiceImplFileName("%sServiceImpl")

                            .mapperBuilder().enableFileOverride().enableBaseResultMap().enableBaseColumnList()
                            .entityBuilder().enableFileOverride().enableLombok().idType(IdType.ASSIGN_ID)
                            //.enableActiveRecord()
                            .superClass(DOMAIN_BASE_ENTITY)
                            .naming(NamingStrategy.underline_to_camel)
                            .columnNaming(NamingStrategy.underline_to_camel)
                            .addSuperEntityColumns(BASE_COLUMNS)
                            //.enableChainModel()
                            .addTableFills(new Column("create_time", FieldFill.INSERT))
                            .addTableFills(new Column("update_time", FieldFill.INSERT_UPDATE))
                            .logicDeleteColumnName("deleted").logicDeletePropertyName("deleted")
                            .versionPropertyName("version").versionColumnName("version")


                    ;
                })
                //.templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板，默认的是Velocity引擎模板
                .templateConfig(builder -> {
                    builder.controller("vm/mybatis-plus/controller.java")
                            .service("vm/mybatis-plus/service.java")
                            .serviceImpl("vm/mybatis-plus/serviceImpl.java")
                            .entity("vm/mybatis-plus/domain.java")
                            .mapper("vm/mybatis-plus/mapper.java")
                            .xml("vm/mybatis-plus/mapper.xml")

//                            .xml("vm/vue/v3/index.vue.vm")

                    ;
                })
                .execute();
//        entityGenerator();
    }


}
